from django.shortcuts import render, redirect
from django.views import View
from django import http
import re, json
from django.contrib.auth import login, logout, authenticate
from django_redis import get_redis_connection
# from django.conf.global_settings import SESSION_COOKIE_AGE
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError

from .models import User, Address
from meiduo_mall.utils.views import LoginRequiredView
from meiduo_mall.utils.response_code import RETCODE
from celery_tasks.email.tasks import send_verify_email
from .utils import generate_email_verify_url, get_user_token
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis
import logging

logger = logging.getLogger('django')

class RegisterView(View):
    """注册"""

    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        """注册逻辑"""
        # 1.获取请求体表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')  # 勾选 'on'  没有勾选 None

        # 2.前端数据拿到后端使用之前都必须校验
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20个字符的密码')
        if password != password2:
            return http.HttpResponseForbidden('输入两次密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号')
        #  短信验证码校验逻辑后期补充
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 获取redis数据库中当前手机号所对应的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 如果相让短信验证码只能用一次,取出后就从redis删除
        redis_conn.delete('sms_%s' % mobile)
        # 判断短信验证码是否已过期
        if sms_code_server is None:
            # return http.HttpResponse('短信验证码已过期')
            return render(request, 'register.html', {'register_errmsg': '短信短信已过期'})
        # 将redis取出来bytes类型的短信验证码转换成str
        sms_code_server = sms_code_server.decode()
        # 用户填写的短信验证码和redis存的是否一样
        if sms_code != sms_code_server:
            return render(request, 'register.html', {'register_errmsg': '短信验证码填写错误'})

        # 3. 新增User模型对象
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 状态保持
        login(request, user)  # 状态保持原理: 将当前用户的id值存储到session中  JWT
        # 4. 响应
        # return http.HttpResponse('注册成功即代表登录成功,跳转到首页')
        response = redirect('/')
        response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)

        return response


class UsernameCountView(View):
    """判断用户名是否重复"""

    def get(self, request, username):
        # 以用户名查询user获取count
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'count': count})


class MobileCountView(View):
    """判断手机号是否重复"""

    def get(self, request, mobile):
        # 以手机号查询user获取count
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'count': count})


class LoginView(View):
    """登录视图"""

    def get(self, request):
        return render(request, 'login.html')

    # def post(self, request):
    #     # 1. 接收请求表单数据
    #     query_dict = request.POST
    #     username = query_dict.get('username')
    #     password = query_dict.get('password')
    #     remembered = query_dict.get('remembered')
    #     # 2. 校验
    #     if all([username, password]) is False:
    #         return http.HttpResponseForbidden('缺少必传参数')
    #     from django.db.models import Q
    #     try:
    #         user = User.objects.get(Q(username=username) | Q(mobile=username))
    #         if user.check_password(password) is False:
    #             return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
    #     except User.DoesNotExist:
    #         return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
    #     # 3. 校验用户名和密码是否正确
    #     # user = authenticate(request, username=username, password=password)
    #     # if user is None:
    #     #     return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
    #
    #     # 4. 状态保持
    #     login(request, user)
    #     # 如果用户没有勾选记住登录
    #     if remembered is None:
    #         request.session.set_expiry(0)  # 如果没有记住登录,关闭浏览器就过期(会话结束)
    #     # 5. 重定向到首页
    #     return http.HttpResponse('登录成功,跳转到首页')

    def post(self, request):
        # 1. 接收请求表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')
        # 2. 校验
        if all([username, password]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        # User.USERNAME_FIELD = 'mobile'
        # 3. 校验用户名和密码是否正确
        user = authenticate(request, username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 4. 状态保持
        login(request, user)
        # 如果用户没有勾选记住登录
        if remembered is None:
            request.session.set_expiry(0)  # 如果没有记住登录,关闭浏览器就过期(会话结束)
        # 5. 重定向到首页
        # return http.HttpResponse('登录成功,跳转到首页')
        # 创建响应对象
        response = redirect(request.GET.get('next') or '/')  # 如果界面来来源,登录成功去指定界面,没有来源默认去首页
        # 登录成功向cookie中存储username
        # if remembered is None:
        #     response.set_cookie('username', user.username, max_age=None)
        # else:
        #     response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)
        response.set_cookie('username', user.username,
                            max_age=None if remembered is None else settings.SESSION_COOKIE_AGE)
        merge_cart_cookie_to_redis(request, response)
        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        # 清除状态保持
        logout(request)

        # 重定向到登录界面
        response = redirect('/login/')
        # 删除cookie中的username
        response.delete_cookie('username')

        return response


# from django.utils.decorators import method_decorator
# from django.contrib.auth.decorators import login_required
class InfoView(LoginRequiredMixin, View):
    """用户中心"""

    # def get(self, request):
    #     # 获取请求中的user
    #     user = request.user
    #     # isinstance(user, User)
    #     if user.is_authenticated:  # 如果成立说明是登录用户
    #         return render(request, 'user_center_info.html')
    #     else:  # 如果没有登录,重定向到登录界面
    #         return redirect('/login/?next=/info/')
    # @method_decorator(login_required)
    def get(self, request):
        return render(request, 'user_center_info.html')


# print(InfoView.__mro__)
# print(LoginRequiredMixin.__mro__)

class EmailView(LoginRequiredView):
    """设置用户邮箱及发送邮箱"""

    def put(self, request):
        # 1.接收请求体非表单数据
        data_bytes = request.body
        data_str = data_bytes.decode()
        json_dict = json.loads(data_str)
        email = json_dict.get('email')
        # 2.校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('邮箱格式有误')
        # 3. 修改email, save

        user = request.user
        # 如果用户没有设置过邮箱再来设置
        if user.email != email:
            user.email = email
            user.save()

        # 发送邮箱
        # from django.core.mail import send_mail
        # send_mail(subject='哇哈哈',
        #           message='哈哈哇',
        #           from_email=settings.EMAIL_FROM,
        #           recipient_list=[email],
        #           html_message='<a href="http://www.baidu.com">百度一下</a>')
        verify_url = generate_email_verify_url(user)
        send_verify_email.delay(email, verify_url)
        # 响应json
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class EmailVerifyView(View):
    """激活邮箱"""

    def get(self, request):
        # 1.接收查询参数
        token = request.GET.get('token')
        # 2.对token解密
        user = get_user_token(token)
        # 3. 判断是否有user
        if user is None:
            return http.HttpResponseForbidden('token无效')
        # 修改user.email_active字段
        user.email_active = True
        user.save()
        # 4.响应
        return redirect('/info/')


class AddressesView(LoginRequiredView):
    """展示收货地址界面"""

    def get(self, request):
        user = request.user
        # 获取当前用户所有未被逻辑删除的收货地址
        address_qs = Address.objects.filter(user=user, is_deleted=False)
        # user.addresses.filter(is_delete=False)
        # 定义一个列表用来保存所有的收货地址字典
        address_list = []
        for address in address_qs:
            address_list.append({
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email

        })

        context = {
            'addresses': address_list,  # 当前登录用户的所有未被逻辑删除的收货地址
            'default_address_id': user.default_address_id
        }
        return render(request, 'user_center_site.html', context)


class AddressesCreateView(LoginRequiredView):
    """新增收货地址"""

    def post(self, request):
        # 1.接收请求体非表单数据
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 2.校验
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请求输入正确的手机号')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        user = request.user
        # 3.Address 新增  ctrl + alt + L
        try:
            address = Address(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            address.save()
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('数据异常')

        # 判断当前用户是否有默认地址,如果没有就把当前新增的地址设置为用户的默认地址
        if user.default_address is None:
            user.default_address = address
            user.save()

        # 将新增的收货地址模型转字典
        address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email

        }
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})


class UserBrowseHistory(View):
    """保存商品浏览记录"""
    def post(self, request):
        # 判断当前用户是否登录,如果未登录什么也不做
        user = request.user
        if not user.is_authenticated:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
        # 获取请求体数据
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 校验
        try:
            sku = SKU.objects.get(id=sku_id, is_launched=True)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')
        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 拼接redis key
        key = 'history_%s' % user.id
        # 创建管道
        pl = redis_conn.pipeline()
        # 先去重
        # redis_conn.lrem(key, count, value)
        pl.lrem(key, 0, sku_id)
        # 添加到列表的开头
        pl.lpush(key, sku_id)
        # 截取保留列表中前5个元素
        pl.ltrim(key, 0, 4)
        # 执行管道
        pl.execute()
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self, request):
        # 获取user
        user = request.user
        if not user.is_authenticated:
            return http.HttpResponseForbidden('出去')
        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 获取当前用户所有商品浏览记录
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)
        # sku_qs = SKU.objects.filter(id__in=sku_ids)  # 此写法为按id从小到到查询sku
        sku_list = []  # 用来保存一个一个的sku字典
        for sku_id in sku_ids:
            # 根据sku_id查询sku模型
            sku = SKU.objects.get(id=sku_id)
            # 模型转字典
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': sku_list})

